package com.weilele.base.library

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentContainerView
import com.weilele.mvvm.utils.fragment.addFragment
import com.weilele.mvvm.utils.safeGet

/**
 * 包含fragment的activity
 */
open class FragmentContainerActivity : BaseActivity() {
    companion object {
        const val KEY_FRAGMENT_CLS_NAME = "KEY_FRAGMENT_CLS_NAME"
        const val KEY_FRAGMENT_ARGUMENTS = "KEY_FRAGMENT_ARGUMENTS"

        /**
         * 在activity里面启动activity
         */
        inline operator fun <reified F : Fragment> invoke(
            context: Context?,
            arguments: Bundle? = null,
            intentBlock: (Intent) -> Unit = {
                context?.startActivity(it)
            },
        ) {
            start<F, FragmentContainerActivity>(context, arguments, intentBlock)
        }

        /**
         * 在activity里面启动activity
         */
        inline operator fun <reified F : Fragment> invoke(
            fragment: Fragment?,
            arguments: Bundle? = null,
            intentBlock: (Intent) -> Unit = {
                fragment?.startActivity(it)
            },
        ) {
            start<F, FragmentContainerActivity>(fragment?.context, arguments, intentBlock)
        }

        /**
         * 在fragment里面启动activity
         */
        inline fun <reified F : Fragment, reified A : FragmentContainerActivity> start(
            context: Context?,
            arguments: Bundle? = null,
            intentBlock: (Intent) -> Unit,
        ) {
            val intent = Intent(context, A::class.java)
            putFragmentData<F>(intent, arguments)
            intentBlock.invoke(intent)
        }


        /**
         * 将fragment的类对象和将要传递给fragment的bundle数据，写入到intent里面
         */
        inline fun <reified F : Fragment> putFragmentData(
            intent: Intent,
            arguments: Bundle? = null,
        ) {
            intent.putExtra(KEY_FRAGMENT_CLS_NAME, F::class.java)
            arguments?.let {
                intent.putExtra(KEY_FRAGMENT_ARGUMENTS, arguments)
            }
        }
    }

    val fragmentClass by lazy {
        intent.getSerializableExtra(KEY_FRAGMENT_CLS_NAME).safeGet<Class<Fragment>>()
    }

    override fun onMvvmCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): Any? {
        return FragmentContainerView(this).apply {
            id = View.generateViewId()
            fragmentClass?.let {
                addFragment(id, it.newInstance().apply {
                    arguments = intent.getBundleExtra(KEY_FRAGMENT_ARGUMENTS)
                })
            }
        }
    }
}